<template>
  <div class="page">
<scroll-view scroll-y="true" style="height: 100vh;">
    <div class="top">
      <div class="toptexts"><uni-icons type="fire-filled" size="20" color="#FFF"></uni-icons>入库相关</div>
      <div class="topitem">
        <div class="item" @click="jumpurl" data-url="/pages/instock/shouhuo" data-auth="1">
          <image src="@/static/images/instock/shouhuo.png" alt=""></image>
          <div class="toptext">外购入库</div>
        </div>
		<div class="item" @click="jumpurl" data-url="/pages/instock/proin" data-auth="1">
		  <image src="@/static/images/instock/proin.png" alt=""></image>
		  <div class="toptext">产品入库</div>
		</div>
		<!-- <div class="item" @click="jumpurl" data-url="/pages/instock/shangjia" data-auth="1">
		  <image src="@/static/images/instock/add.png" alt=""></image>
		  <div class="toptext">上架</div>
		</div> -->
		<div class="item" @click="jumpurl" data-url="/pages/instock/back" data-auth="1">
		  <image src="@/static/images/instock/back.png" alt=""></image>
		  <div class="toptext">入库退回</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/instock/otherin" data-auth="1">
		  <image src="@/static/images/instock/oin.png" alt=""></image>
		  <div class="toptext">其他入库</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/instock/incheck?pass_status=0" data-auth="1">
		  <image src="@/static/images/instock/incheck.png" alt=""></image>
		  <div class="toptext">外购质检</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/instock/pincheck?status=2" data-auth="1">
		  <image src="@/static/images/instock/pincheck.png" alt=""></image>
		  <div class="toptext">产品质检</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/instock/toyk" data-auth="1">
		  <image src="../../static/images/base/yiku.png" alt=""></image>
		  <div class="toptext">移库</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/instock/assemblein" data-auth="1">
		  <image src="../../static/images/instock/assemble.png" alt=""></image>
		  <div class="toptext">组装单</div>
		</div>
      </div>
    
	<div class="toptexts"><uni-icons type="fire-filled" size="20" color="#FFF"></uni-icons>出库相关</div>
      <div class="topitem">
        <div class="item" @click="jumpurl" data-url="/pages/outstock/pick" data-auth="1">
          <image src="@/static/images/outstock/pick.png" alt=""></image>
          <div class="toptext">生产领料</div>
        </div>
		<div class="item" @click="jumpurl" data-url="/pages/outstock/otherout?order_type=18" data-auth="1">
		  <image src="@/static/images/outstock/add.png" alt=""></image>
		  <div class="toptext">直接领料</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/outstock/sellout" data-auth="1">
		  <image src="@/static/images/outstock/sellout.png" alt=""></image>
		  <div class="toptext">销售出库</div>
		</div>
		<!--  -->
		<div class="item" @click="jumpurl" data-url="/pages/outstock/back" data-auth="1">
		  <image src="@/static/images/instock/back.png" alt=""></image>
		  <div class="toptext">出库退回</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/outstock/otherout?order_type=12" data-auth="1">
		  <image src="@/static/images/outstock/oout.png" alt=""></image>
		  <div class="toptext">其他出库</div>
		</div>
		<!-- <div class="item" @click="jumpurl" data-url="/pages/outstock/sellout_tp" data-auth="1">
		  <image src="@/static/images/outstock/sellout.png" alt=""></image>
		  <div class="toptext">销售出库TP</div>
		</div> -->
      </div>
   
   <div class="toptexts"><uni-icons type="fire-filled" size="20" color="#FFF"></uni-icons>数据分析</div>
     <div class="topitem">
   	<div class="item" @click="jumpurl" data-url="/pages/kc/index">
   	  <image src="../../static/images/v4.png" alt=""></image>
   	  <div class="toptext">库存查询</div>
   	</div>
	<div class="item" @click="jumpurl" data-url="/pages/instock/plan">
		<image src="@/static/images/base/plan.png" alt=""></image>
		<div class="toptext">入库任务</div>
	</div>
	<div class="item" @click="jumpurl" data-url="/pages/outstock/appmaterial">
			<image src="@/static/images/v8.png" alt=""></image>
		<div class="toptext">出库任务</div>
	</div>
   </div>
   
	  <div class="toptexts"><uni-icons type="fire-filled" size="20" color="#FFF"></uni-icons>其他管理</div>
	  <div class="topitem">
	    <div class="item" @click="jumpurl" data-url="/pages/allot/add" data-auth="1">
	      <image src="../../static/images/v12.png" alt=""></image>
	      <div class="toptext">调拨</div>
	    </div>
		<div class="item" @click="jumpurl" data-url="/pages/inventory/listcheck" data-auth="1">
		  <image src="../../static/images/v5.png" alt=""></image>
		  <div class="toptext">盘点</div>
		</div>
		<!-- <div class="item" @click="jumpurl" data-url="/pages/kc/mapan">
			<image src="@/static/images/base/mapan.png" alt=""></image>
		<div class="toptext">码盘管理</div>
		</div> -->
	</div>
	
	<div class="toptexts"><uni-icons type="fire-filled" size="20" color="#FFF"></uni-icons>档案管理</div>
	<div class="topitem">
	  <div class="item" @click="jumpurl" data-url="/pages/inventory/index">
			<image src="@/static/images/base/inventory.png" alt=""></image>
			<div class="toptext">物料档案</div>
	  </div>
	  <div class="item" @click="jumpurl" data-url="/pages/shelves/index" style="width: 200rpx;">
			<image src="@/static/images/base/shelves.png" alt=""></image>
			<div class="toptext">库区档案</div>
	  </div>
	</div>
	
	  <div class="toptexts"><uni-icons type="fire-filled" size="20" color="#FFF"></uni-icons>其他操作</div>
	  <div class="topitem">
	    <!-- <div class="item" @click="togetData" v-show="!this.myconfig.online">
	      <image src="../../static/images/v10.png" alt=""></image>
	      <div class="toptext">同步数据</div>
	    </div>
		<div class="item" @click="tobackData">
		  <image src="../../static/images/v11.png" alt=""></image>
		  <div class="toptext">回传数据</div>
		</div> -->
		
		<!-- <div class="item" @click="clearData" data-url="" data-auth="1">
		  <image src="@/static/images/base/clear.png" alt=""></image>
		  <div class="toptext">清空数据</div>
		</div> -->
		<!-- <div class="item"></div> -->
		
		<div class="item" data-url="" data-auth="1">
		  <stockSelect :stock_id.sync="user.stock_id" show_type="button"></stockSelect>
		  <div class="toptext">切换仓库</div>
		</div>
		<div class="item" @click="jumpurl" data-url="/pages/config/list">
		  <image src="../../static/images/v3.png" alt=""></image>
		  <div class="toptext">配置</div>
		</div>
	  </div>
	</div>
</scroll-view>
  </div>
</template>
<script>
import stockSelect from "@/component/stockhouse.vue"
export default {
  data() {
    return {
    	myconfig: {},
		syn_num:0,//同步数量
		insert_num:0,
		syntime:'',
		clickflag:true,
		user:''
    }
  },
  components: {
  	stockSelect
  },
  mounted() {},
  onLaunch() {},
  onShow() {
	this.user = uni.getStorageSync('user')
	//没有登录跳到登录页
	if(!uni.getStorageSync('user')){
	  	uni.reLaunch({
	  		url:'/pages/index/login',
	  		success() {
				//关闭其他页面，直接到登录页
	  			plus.navigator.closeSplashscreen()}
	  	})
	}
	  
	//加载配置
  	if(uni.getStorageSync('myconfig')!=''){
  		this.myconfig = uni.getStorageSync('myconfig')
  	}else{
		uni.showToast({
		  title: '请先初始化配置',
		  icon: 'error',
		  duration: 2000,
		  success: function () {
		    // 提示信息显示成功后执行跳转
		    uni.navigateTo({
		      url: '/pages/config/set' // 跳转到目标页面
		    });
		  }
		});
	}
	
	//监听下载
	let downloadOK = 0
	uni.$off('downloadOK')
	uni.$on('downloadOK',(filename) => {
		downloadOK++
		if(this.syn_num == downloadOK){
			console.log('全部下载完成')
		}
		//下载完，开始插入数据
		this.$Db.addAsyncData(filename).catch(err=>{
			this.$Db.addlog('同步数据'+filename,err)
			this.$Api.msg(err)
		})
	})
	
	//回传操作日志
	this.$Db.synActionLog(this.user.userid)
	
	//同步同时获得最大单号，更新本机pda
	let date = this.$Func.getDateTime('today','Ymd')
	this.$Api.getTodayMaxCode(date).then(res => {
		if(res.data.code){
			//自动重置此pda最新单号
			if(res.data.data.length>0){
				for(let arr of res.data.data){
					this.$Db.setMcode(date,arr.pre_str,arr.max_num)
				}
			}
		}else{
			this.$Api.msg(res.data.msg)
		}
	})
	
	//更新标题
	this.$Func.setBarTitle()
  },
  watch:{
	insert_num(new_val,old_val){
		console.log(new_val,this.syn_num)
		if(new_val>0 && new_val == this.syn_num){
			console.log('完成插入操作，等待解锁')
			uni.setStorageSync('backDataFlag',false)
			uni.setStorageSync('syntime',this.syntime)
			uni.hideLoading()
		}
	}  
  },
  onLoad() {
  	if(!this.$Db.isOpen()){
		//打开数据库
		this.$Db.openSqlite()
	}
	
	//this.$Db.exeSQL("UPDATE stockbill SET syn_status = '0' WHERE FBillNo='OIN231101005'")
	//this.$Db.deleteTableData('stockbill')
	//this.$Db.deleteTableData('stockbillentry') 
	//this.$Db.dropTable('shelves')invShelvesLatest
	//stockbill stockbillentry 
	// this.$Db.selectTableData('stockbill').then(res=>{
	// 	console.log(res)
	// }).catch(err=>{
	// 	console.log(err) 
	// }) 
	

	//监听插入动作
	uni.$on('indexAddInsertNum',(pp)=>{
		this.insert_num ++
	})
  },
  methods: {
	  /* onNavigationBarButtonTap(){
		  console.log(123)
	  }, */
    jumpurl(e) {
		//是否需要验证有无回传标识
		if(e.currentTarget.dataset.auth == 1&&!this.myconfig.online){
			let backDataFlag = uni.getStorageSync('backDataFlag')
			if(backDataFlag){
				this.$Api.msg('请先同步数据','error')
				return 
			}
		}
		
		uni.showLoading({
			mask:true
		})
		var url = e.currentTarget.dataset.url
		/* if(url == '/pages/instock/proin'||url == '/pages/outstock/sellout'){
			this.$Api.msg('功能待开放')
			uni.hideLoading()
			return
		} */
		if(url!='/pages/config/list'){
			if(!this.$Func.checkUserAuth(url)){
				return 
			}
		}
		
		uni.navigateTo({
			url: url,
			success() {
				uni.hideLoading()
			}
		});
    },
	togetData(){
		let _this = this
		if(!this.clickflag){
			return 
		}
		this.clickflag = false
		setTimeout(function(){
			//1秒后才给点同步，防止并发
			_this.clickflag = true
		},1000); 
		
		this.$Api.getSyntime().then(res=>{
			if(res.statusCode==200){
				if(res.data.datetime!=''&&res.data.datetime!=undefined){
					if(uni.getStorageSync('syntime')==res.data.datetime){
						this.$Api.msg('暂无最新数据','error')
						return 
					}else{
						this.syntime = res.data.datetime
						uni.showModal({
							title: '温馨提醒',
							content: '确定要同步数据？',
							success: function (res) {
								if (res.confirm) {
									_this.getData()
								}
						}})
					}
				 }else{
					 uni.showModal({
					 	title: '温馨提醒',
					 	content: '确定要同步数据？',
					 	success: function (res) {
					 		if (res.confirm) {
					 			_this.getData()
					 		}
					 }})
				 }
			}
		})
	},
   async getData(){
		if(!Array.isArray(this.myconfig.syn_filename_arr)){
			this.$Api.msg('请先保存设置','error')
			return
		}
		
		if(!this.myconfig.syn_filename_arr.length){
			this.$Api.msg('暂无同步数据','error')
			return
		}
		if(uni.getStorageSync('backDataFlag')&&!this.myconfig.syn_kc){
			this.$Api.msg('请开启同步库存','error')
			return
		}
		
		//判断本地是否有待处理单据，收货和源单出库
		let exist_res = ''
		await this.$Db.checkExistStockbillNosynByType([0,3],'id').then(res=>{
			if(res.length>0){
				exist_res = res
			}
		}).catch(err=>{
			this.addlog('点同步操作',err)
		})
		
		if(exist_res!=''){
			this.$Api.msg('存在待回传单据,请先回传')
			return 
		}
		
		this.$Api.getPcBillStatus().then(res=>{
			//后台无待处理单据才能同步
			uni.showLoading({
				title:'同步中...',
				mask:true
			});
			
			//下载json数据，并创建表格
			this.syn_num = 0
			this.insert_num = 0
			try{
				for(let fname of this.myconfig.syn_filename_arr){
					this.getJsonUrl(fname,true);
				}
				
				//同步同时获得最大单号，更新本机pda
				this.$Api.getTodayMaxCode().then(res => {
					if(res.data.data.length>0){
						let date = this.$Func.getDateTime('today','Ymd')
						for(let arr of res.data.data){
							this.$Db.setMcode(date,arr.pre_str,arr.max_num)
						}
					}
				})
				
				//同步同时针对已回传但未变更状态的单据
				this.$Db.synPdaPcOrderStatus(this.user)
			}catch(e){
				uni.hideLoading()
				this.$Api.msg(e)
			}
			
		}).catch(err=>{
			this.$Api.msg(err)
		})
	},
	tobackData(){
		let _this = this
		if(!this.clickflag){
			return 
		}
		this.clickflag = false
		setTimeout(function(){
			//1秒后才给点同步，防止并发
			_this.clickflag = true
		},1000); 
		
		uni.showModal({
			title: '温馨提醒',
			content: '确定要回传数据？',
			success: function (res) {
				if (res.confirm) {
					_this.backData()
				}
		}})
	},
	//回传数据
	backData(){
		if (this.$Func.onNetWork() !== 'none') {
			uni.showLoading({
				mask:true,
				title:'数据回传中...'
			})
			this.$Db.backSynAllData(this.user,this.myconfig.online).then(res=>{
				uni.hideLoading()
				this.$Api.msg('回传成功','success')
			})
			.catch(err=>{
				uni.hideLoading()
				this.$Db.addlog('回传数据',err) 
				this.$Api.msg(err)
			})
		}
	},
	//下载并创建基础表
	getJsonUrl(fname,tname = false){
		//针对固定数据，用这个
		let _this = this
		this.$Api.getJsonUrl(fname).then(res => {
			if(res.data.code == 1){
				if(fname == 'inventory'){
					if(res.data.data.length>0){
						this.syn_num+=res.data.data.length
						res.data.data.forEach((url,index)=>{
							index++
							_this.$Api.toCopy(fname+index+'.json',url)
						})
					}
				}else{
					this.syn_num++
					_this.$Api.toCopy(fname+'.json',res.data.data)
				}
			}else{
				_this.$Api.msg(res.data.msg);
			}
		}).then(res => {
			//同时先删除、后建表
			_this.$Db.synBaseData(fname);
			return true
		}).catch(err=>{
			_this.$Db.addlog('首页同步',err);
			throw(err)
		})
	},
	//设置完成插入数据，数量
	indexSetSynNum(flag){
		console.log(flag)
		this.insert_num++
	}
  },
}
</script>

<style lang="less">
page {
  width: 100%;
  height: 100%;
  background: linear-gradient(179.88deg, #DCE9FE 0%, #FFFFFF 35%);
}
</style>